import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/features/post/viewmodels/publish_post_viewmodel.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/models/photo_params.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/url_open.dart';
import 'package:vista/shared/utils/widget_extension.dart';

/// 发布动态视图
/// 发布动态功能页面
class PublishPostView extends StatefulWidget {
  const PublishPostView({super.key});

  @override
  State<PublishPostView> createState() => _PublishPostViewState();
}

class _PublishPostViewState extends State<PublishPostView> {
  late TextEditingController _contentController;

  @override
  void initState() {
    super.initState();
    _contentController = TextEditingController();
  }

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<PublishPostViewModel>.reactive(
      viewModelBuilder: () => PublishPostViewModel(getIt.get(), getIt.get()),
      builder: (context, viewModel, child) {
        return Scaffold(
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my-background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: [
                // 顶部标题栏
                _buildHeader(context),
                // 可滚动内容
                Expanded(
                  child: SingleChildScrollView(
                    child: [
                          SizedBox(height: 20.h),
                          // 发布内容卡片
                          _buildContentCard(context, viewModel),
                          SizedBox(height: 20.h),
                          // 参数按钮（仅摄影类型显示）
                          if (viewModel.selectedCategory ==
                              PostCategory.photography)
                            _buildParametersButton(context, viewModel),
                          SizedBox(height: 100.h), // 底部留白
                        ]
                        .verticalShot(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                        )
                        .frameHorizontal(14.w),
                  ),
                ),
                // 底部确认按钮和 EULA 链接
                _buildBottomSection(context, viewModel),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
            ),
          ),
        );
      },
    );
  }

  /// 构建顶部标题栏
  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Image.asset(
              'assets/images/back.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
          Expanded(
            child: Center(
              child: Text(
                'Dynamic Release',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w800,
                  fontFamily:
                      GoogleFonts.alegreyaSans(
                        fontWeight: FontWeight.w800,
                      ).fontFamily,
                  color: Colors.black,
                ),
              ),
            ),
          ),
          SizedBox(width: 24.w), // 平衡返回按钮
        ],
      ),
    );
  }

  /// 构建内容卡片
  Widget _buildContentCard(
    BuildContext context,
    PublishPostViewModel viewModel,
  ) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
        boxShadow: [
          BoxShadow(
            color: Color(0xFF000000),
            blurRadius: 0,
            offset: Offset(1, 1),
            spreadRadius: 0,
          ),
        ],
        border: Border.all(color: Colors.black.withOpacity(0.1), width: 1.w),
      ),
      padding: EdgeInsets.all(14.w),
      child: [
        // 分类选择
        _buildCategorySelector(context, viewModel),
        SizedBox(height: 20.h),
        // 文本输入框
        _buildTextInput(context, viewModel),
        SizedBox(height: 20.h),
        // 图片选择和预览
        _buildImageSelector(context, viewModel),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  /// 构建分类选择器
  Widget _buildCategorySelector(
    BuildContext context,
    PublishPostViewModel viewModel,
  ) {
    return Row(
      children: [
        Expanded(
          child: GestureDetector(
            onTap: () => viewModel.setCategory(PostCategory.dailyLife),
            child: Row(
              children: [
                Text(
                  'Daily Life',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w400,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                    color: Colors.black87,
                  ),
                ),
                const Spacer(),
                Radio<PostCategory>(
                  value: PostCategory.dailyLife,
                  groupValue: viewModel.selectedCategory,
                  onChanged: (value) {
                    if (value != null) {
                      viewModel.setCategory(value);
                    }
                  },
                ),
              ],
            ),
          ),
        ),
        SizedBox(width: 20.w),
        Expanded(
          child: GestureDetector(
            onTap: () => viewModel.setCategory(PostCategory.photography),
            child: Row(
              children: [
                Text(
                  'Photography',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w400,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                    color: Colors.black87,
                  ),
                ),
                const Spacer(),
                Radio<PostCategory>(
                  value: PostCategory.photography,
                  groupValue: viewModel.selectedCategory,
                  onChanged: (value) {
                    if (value != null) {
                      viewModel.setCategory(value);
                    }
                  },
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建文本输入框
  Widget _buildTextInput(BuildContext context, PublishPostViewModel viewModel) {
    return TextField(
      controller: _contentController,
      onChanged: viewModel.setContent,
      maxLines: 5,
      style: TextStyle(
        fontSize: 16.sp,
        color: Colors.black87,
        fontFamily:
            GoogleFonts.alegreyaSans(fontWeight: FontWeight.w400).fontFamily,
      ),
      decoration: InputDecoration(
        hintText: 'Add the main text',
        hintStyle: TextStyle(
          color: Colors.grey[400],
          fontSize: 16.sp,
          fontFamily:
              GoogleFonts.alegreyaSans(fontWeight: FontWeight.w400).fontFamily,
        ),
        filled: true,
        fillColor: Colors.grey[100],
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
          borderSide: BorderSide.none,
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
          borderSide: BorderSide.none,
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
          borderSide: BorderSide(color: ColorConstants.accentColor, width: 2),
        ),
        contentPadding: EdgeInsets.all(16.w),
      ),
    );
  }

  /// 构建图片选择器
  Widget _buildImageSelector(
    BuildContext context,
    PublishPostViewModel viewModel,
  ) {
    return Row(
      children: [
        for (int i = 0; i < 3; i++) ...[
          Expanded(child: _buildImageItem(context, viewModel, i)),
          if (i < 2) SizedBox(width: 12.w),
        ],
      ],
    );
  }

  /// 构建单个图片项
  Widget _buildImageItem(
    BuildContext context,
    PublishPostViewModel viewModel,
    int index,
  ) {
    final hasImage = index < viewModel.selectedImages.length;
    final imagePath = hasImage ? viewModel.selectedImages[index] : null;

    return GestureDetector(
      onTap: () => viewModel.selectImages(context),
      child: AspectRatio(
        aspectRatio: 1,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(8.r),
            border: Border.all(
              color: Colors.black.withOpacity(0.1),
              width: 1.w,
            ),
          ),
          child:
              hasImage && imagePath != null
                  ? Stack(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(8.r),
                        child: _buildImage(imagePath),
                      ),
                      // 删除按钮
                      Positioned(
                        top: 4.w,
                        right: 4.w,
                        child: GestureDetector(
                          onTap: () => viewModel.removeImage(index),
                          child: Container(
                            width: 24.w,
                            height: 24.w,
                            decoration: BoxDecoration(
                              color: Colors.red,
                              shape: BoxShape.circle,
                            ),
                            child: Icon(
                              Icons.close,
                              size: 16.w,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                      // 图片序号
                      Positioned(
                        bottom: 4.w,
                        left: 4.w,
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 6.w,
                            vertical: 2.h,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.5),
                            borderRadius: BorderRadius.circular(4.r),
                          ),
                          child: Text(
                            '${index + 1}/3',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.white,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ],
                  )
                  : Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.add_circle_outline,
                          size: 32.w,
                          color: Colors.grey[400],
                        ),
                        SizedBox(height: 4.h),
                        Text(
                          '${index + 1}/3',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ],
                    ),
                  ),
        ),
      ),
    );
  }

  /// 构建图片 Widget
  Widget _buildImage(String imagePath) {
    // 判断是本地文件路径还是asset路径
    if (imagePath.startsWith('/') || imagePath.startsWith('file://')) {
      // 本地文件路径
      final filePath =
          imagePath.startsWith('file://')
              ? imagePath.replaceFirst('file://', '')
              : imagePath;
      return Image.file(
        File(filePath),
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey[300],
            child: Icon(Icons.broken_image, size: 40.w, color: Colors.grey),
          );
        },
      );
    } else {
      // asset路径
      return Image.asset(
        imagePath,
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey[300],
            child: Icon(Icons.broken_image, size: 40.w, color: Colors.grey),
          );
        },
      );
    }
  }

  /// 构建参数按钮
  Widget _buildParametersButton(
    BuildContext context,
    PublishPostViewModel viewModel,
  ) {
    return GestureDetector(
      onTap: () async {
        final params = await Navigator.of(context).push<PhotoParams>(
          MaterialPageRoute(
            builder:
                (_) => PhotoParamsView(initialParams: viewModel.photoParams),
          ),
        );
        if (params != null) {
          viewModel.setPhotoParams(params);
        }
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 16.h),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Color(0xFF000000),
              blurRadius: 0,
              offset: Offset(1, 1),
              spreadRadius: 0,
            ),
          ],
          borderRadius: BorderRadius.circular(8.r),
          border: Border.all(color: Colors.black, width: 1.w),
        ),
        child: Row(
          children: [
            Text(
              'Parameters',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
                fontFamily:
                    GoogleFonts.alegreyaSans(
                      fontWeight: FontWeight.w400,
                    ).fontFamily,
                color: Colors.black87,
              ),
            ),
            const Spacer(),
            Icon(Icons.chevron_right, size: 20.w, color: Colors.black54),
          ],
        ),
      ),
    );
  }

  /// 构建底部区域
  Widget _buildBottomSection(
    BuildContext context,
    PublishPostViewModel viewModel,
  ) {
    return Container(
      padding: EdgeInsets.fromLTRB(14.w, 0, 14.w, 20.h),
      child: [
        // 确认按钮
        ElevatedButton(
          onPressed:
              viewModel.isBusy
                  ? null
                  : () async {
                    final success = await viewModel.publishPost();
                    if (context.mounted) {
                      if (success) {
                        FlashNotifier.flashSuccess(
                          'Post published successfully',
                        );
                        Navigator.of(context).pop(true);
                      } else {
                        FlashNotifier.flashError('Failed to publish post');
                      }
                    }
                  },
          style: ElevatedButton.styleFrom(
            padding: EdgeInsets.symmetric(vertical: 16.h),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12.r),
            ),
            backgroundColor: ColorConstants.accentColor,
            foregroundColor: Colors.white,
            elevation: 0,
          ),
          child: Text(
            'Confirm',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              fontFamily:
                  GoogleFonts.alegreyaSans(
                    fontWeight: FontWeight.w600,
                  ).fontFamily,
            ),
          ),
        ),
        SizedBox(height: 12.h),
        // EULA 链接
        Center(
          child: GestureDetector(
            onTap: UrlOpen.openEulaUrl,
            child: Text(
              'EULA',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black,
                decoration: TextDecoration.underline,
              ),
            ),
          ),
        ),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
    );
  }
}

/// 摄影参数填写页面
class PhotoParamsView extends StatefulWidget {
  final PhotoParams? initialParams;

  const PhotoParamsView({super.key, this.initialParams});

  @override
  State<PhotoParamsView> createState() => _PhotoParamsViewState();
}

class _PhotoParamsViewState extends State<PhotoParamsView> {
  late TextEditingController _lensController;
  late TextEditingController _flController;
  late TextEditingController _flashController;
  late TextEditingController _exposureController;
  late TextEditingController _cameraController;
  late TextEditingController _isoController;
  late TextEditingController _shutterController;
  late TextEditingController _apertureController;

  @override
  void initState() {
    super.initState();
    final params = widget.initialParams;
    _lensController = TextEditingController(text: params?.lens ?? '');
    _flController = TextEditingController(text: params?.fl ?? '');
    _flashController = TextEditingController(text: params?.flash ?? '');
    _exposureController = TextEditingController(text: params?.exposure ?? '');
    _cameraController = TextEditingController(text: params?.camera ?? '');
    _isoController = TextEditingController(text: params?.iso ?? '');
    _shutterController = TextEditingController(text: params?.shutter ?? '');
    _apertureController = TextEditingController(text: params?.aperture ?? '');
  }

  @override
  void dispose() {
    _lensController.dispose();
    _flController.dispose();
    _flashController.dispose();
    _exposureController.dispose();
    _cameraController.dispose();
    _isoController.dispose();
    _shutterController.dispose();
    _apertureController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my-background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: [
            // 顶部标题栏
            _buildHeader(context),
            // 可滚动内容
            Expanded(
              child: SingleChildScrollView(
                child: [
                      SizedBox(height: 20.h),
                      // 参数输入卡片
                      _buildParamsCard(context),
                      SizedBox(height: 100.h), // 底部留白
                    ]
                    .verticalShot(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                    )
                    .frameHorizontal(14.w),
              ),
            ),
            // 底部保存按钮
            _buildSaveButton(context),
          ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
        ),
      ),
    );
  }

  /// 构建顶部标题栏
  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Image.asset(
              'assets/images/back.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
          Expanded(
            child: Center(
              child: Text(
                'Parameters',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w800,
                  fontFamily:
                      GoogleFonts.alegreyaSans(
                        fontWeight: FontWeight.w800,
                      ).fontFamily,
                  color: Colors.black,
                ),
              ),
            ),
          ),
          SizedBox(width: 24.w), // 平衡返回按钮
        ],
      ),
    );
  }

  /// 构建参数输入卡片
  Widget _buildParamsCard(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.black.withOpacity(0.1), width: 1.w),
      ),
      padding: EdgeInsets.all(14.w),
      child: [
        // 参数输入项
        _buildParamField('Lens', _lensController),
        SizedBox(height: 16.h),
        _buildParamField('FL', _flController),
        SizedBox(height: 16.h),
        _buildParamField('Flash', _flashController),
        SizedBox(height: 16.h),
        _buildParamField('Exposure', _exposureController),
        SizedBox(height: 16.h),
        _buildParamField('Camera', _cameraController),
        SizedBox(height: 16.h),
        _buildParamField('ISO', _isoController),
        SizedBox(height: 16.h),
        _buildParamField('Shutter', _shutterController),
        SizedBox(height: 16.h),
        _buildParamField('Aperture', _apertureController),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  /// 构建参数输入字段
  Widget _buildParamField(String label, TextEditingController controller) {
    return [
      Text(
        label,
        style: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w600,
          fontFamily:
              GoogleFonts.alegreyaSans(fontWeight: FontWeight.w600).fontFamily,
          color: Colors.black87,
        ),
      ),
      SizedBox(height: 8.h),
      TextField(
        controller: controller,
        style: TextStyle(
          fontSize: 16.sp,
          color: Colors.black87,
          fontFamily:
              GoogleFonts.alegreyaSans(fontWeight: FontWeight.w400).fontFamily,
        ),
        decoration: InputDecoration(
          hintText: 'Enter $label',
          hintStyle: TextStyle(
            color: Colors.grey[400],
            fontSize: 16.sp,
            fontFamily:
                GoogleFonts.alegreyaSans(
                  fontWeight: FontWeight.w400,
                ).fontFamily,
          ),
          filled: true,
          fillColor: Colors.grey[100],
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8.r),
            borderSide: BorderSide.none,
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8.r),
            borderSide: BorderSide.none,
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8.r),
            borderSide: BorderSide(color: ColorConstants.accentColor, width: 2),
          ),
          contentPadding: EdgeInsets.symmetric(
            horizontal: 16.w,
            vertical: 16.h,
          ),
        ),
      ),
    ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start);
  }

  /// 构建保存按钮
  Widget _buildSaveButton(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(14.w, 0, 14.w, 20.h),
      child: ElevatedButton(
        onPressed: () {
          final params = PhotoParams(
            lens: _lensController.text.trim(),
            fl: _flController.text.trim(),
            flash: _flashController.text.trim(),
            exposure: _exposureController.text.trim(),
            camera: _cameraController.text.trim(),
            iso: _isoController.text.trim(),
            shutter: _shutterController.text.trim(),
            aperture: _apertureController.text.trim(),
          );
          Navigator.of(context).pop(params);
        },
        style: ElevatedButton.styleFrom(
          padding: EdgeInsets.symmetric(vertical: 16.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
          ),
          backgroundColor: ColorConstants.accentColor,
          foregroundColor: Colors.white,
          elevation: 0,
        ),
        child: Text(
          'Save',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            fontFamily:
                GoogleFonts.alegreyaSans(
                  fontWeight: FontWeight.w600,
                ).fontFamily,
          ),
        ),
      ),
    );
  }
}
